package cn.wen.eeayjoke.ui;


import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.wen.base.adapter.recyclerview.QuickRecyclerAdapter;
import cn.wen.base.adapter.recyclerview.QuickRecyclerViewHolder;
import cn.wen.base.decoration.GridItemDecoration;
import cn.wen.core.http.OkHttpPresenter;
import cn.wen.core.titlebar.DefTitleBar;
import cn.wen.core.ui.AppActivity;
import cn.wen.eeayjoke.R;
import cn.wen.eeayjoke.config.URLConfig;
import cn.wen.eeayjoke.config.URLS;
import cn.wen.eeayjoke.entity.bean.base.ResponseHead;
import cn.wen.eeayjoke.entity.bean.login.LoginBean;
import cn.wen.eeayjoke.entity.data.LoginData;
import cn.wen.eeayjoke.net.API;
import cn.wen.eeayjoke.presenter.HttpCallback;
import cn.wen.eeayjoke.presenter.LoginPresenter;
import okhttp3.OkHttpClient;

/**
 * 网络接口测试
 */
public class NetTestActivity extends AppActivity {
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.et_ip)
    EditText mEtIp;
    @BindView(R.id.et_port)
    EditText mEtPort;
    private LoginPresenter presenter = new LoginPresenter();
    private QuickRecyclerAdapter<URLS> mAdapter;
    public static final int TIMEOUT = 30;
    @Override
    public Object getContentLayout() {
        return R.layout.activity_net_test;
    }

    @Override
    protected void initTitle(DefTitleBar titleBar) {
        titleBar.setTitle("网络接口测试");
    }

    @Override
    protected void initView(View contentView) {
        Map<Integer, URLS> urls = URLS.getURLS();
        List<URLS> list = new ArrayList<>();
        for (Map.Entry<Integer, URLS> me : urls.entrySet()) {
            list.add(me.getValue());
        }
        mAdapter = new QuickRecyclerAdapter<URLS>(getAppActivity(), list, R.layout.item_url) {
            @Override
            protected void convert(QuickRecyclerViewHolder holder, final URLS item, final int position) {
                String url = URLS.getSaveUrl();
                if (item.getBaseUrl().equals(url) || (TextUtils.isEmpty(url) && position == 0)) {
                    holder.setTextColor(R.id.tv_url, Color.RED);
                } else {
                    holder.setTextColor(R.id.tv_url, Color.BLACK);
                }
                holder.setText(R.id.tv_url, position + "-->" + item.getDesc());
                holder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String url = URLS.getSaveUrl();
                        if (item.getBaseUrl().equals(url)) {
                            return;
                        }
                        URLS.saveUrl(item.getBaseUrl(), item.getDesc());
                    }
                });
            }
        };
        mRecyclerView.setLayoutManager(new GridLayoutManager(getAppActivity(), 3));
        mRecyclerView.addItemDecoration(new GridItemDecoration(getAppActivity()));
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 调用登录接口
     */
    public void open(View view) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        //添加retrofit日志打印
//        // 设置超时
//        builder.connectTimeout(TIMEOUT, TimeUnit.SECONDS);
//        builder.readTimeout(TIMEOUT, TimeUnit.SECONDS);
//        builder.writeTimeout(TIMEOUT, TimeUnit.SECONDS);
//
//        builder.hostnameVerifier(new HostnameVerifier() {
//            @Override
//            public boolean verify(String hostname, SSLSession session) {
//                return true;
//            }
//        });
//        builder.sslSocketFactory(HttpsUtils.initSSLSocketFactory(),HttpsUtils.initTrustManager());
//
//        OkHttpClient client = builder.build();
//        // 第2部分：在创建Retrofit实例时通过.baseUrl()设置
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("https://khbapi.imkehou.com/") //设置网络请求的Url地址
//                .client(client)
//                .build();
//        TestService testService = retrofit.create(TestService.class);
//        testService.getPost().enqueue(new Callback<ResponseBody>() {
//            @Override
//            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                try {
//                    String result = response.body().string();
//                    LogUtils.e(result);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onFailure(Call<ResponseBody> call, Throwable t) {
//                t.printStackTrace();
//                LogUtils.e(t.getMessage());
//            }
//        });

       LoginData loginData = new LoginData("13556285219", "123456");
//        presenter.login(loginData, new DialogObserver<LoginBean>(getAppActivity()) {
//            @Override
//            public void onResponse(LoginBean data) {
//                // TODO 做登录的成功的操作
//                data.cache();
//                Toast.makeText(getAppActivity(), "" + data.userInfo.nickName, Toast.LENGTH_SHORT).show();
//            }
//        });


       OkHttpPresenter okHttpPresenter = new OkHttpPresenter(getAppActivity());
        String baseUrl = URLConfig.getInstance().baseUrl();
        okHttpPresenter.post(baseUrl + API.LOGIN, loginData, new HttpCallback<LoginBean>() {
            @Override
            public void onSucceed(ResponseHead head, LoginBean data) {
                data.cache();
                Toast.makeText(getAppActivity(), "" + data.userInfo.nickName, Toast.LENGTH_SHORT).show();
            }
        }, true);
    }

    /**
     * 切换IP
     */
    public void change(View view) {
        String ip = getEtText(mEtIp);
        String port = getEtText(mEtPort);
        if (TextUtils.isEmpty(ip)) {
            showToast("请输入IP");
            return;
        }
        if (TextUtils.isEmpty(port)) {
            showToast("请输入端口");
            return;
        }
        String url = "http://192.168.1." + ip + ":" + port;
        URLS.saveUrl(url, ip);
    }

    private void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
}
